// router.js

var User       = Domain.User;
var Message    = Domain.Message;
var Club       = Domain.Club;

var ObjectID   = require('mongodb').ObjectID;
var mongoose   = require('mongoose');

module.exports = function(app, passport) {

   app.get('/', function(req, res) {
      res.render('index', {user: req.user}); 
   });

   app.get('/login', function(req, res) {
      res.render('login', { message: req.flash('loginMessage') });
   }).post('/login', passport.authenticate('my-local-login', {         // passport.authenticate('...') = (req, res, next) middleware
      successRedirect : '/profile', 
      failureRedirect : '/login',   
      failureFlash : true // allow flash messages
   }));

   app.get('/signup', function(req, res) {
      res.render('signup', { message: req.flash('signupMessage') });
   }).post('/signup', passport.authenticate('my-local-signup', {       // passport.authenticate('...') = (req, res, next) middleware
      successRedirect : '/profile', 
      failureRedirect : '/signup', 
      failureFlash : true // allow flash messages
   }));

   app.get('/profile', isLoggedIn, function(req, res) {                 // isLoggedIn = (req, res, next) middleware
      res.render('profile', {user: req.user});
   });

   app.get('/profile/settings', isLoggedIn, function(req, res) {
      res.render('profilesettings', {user: req.user, message: req.flash('profilesettingsMessage') });
   }).post('/profile/settings', isLoggedIn, function(req, res){
      User.update({_id: req.user._id},
         {
            firstname    : req.body.firstname,
            lastname     : req.body.lastname
         }, function(err, num){
            if(err) throw err;
            res.redirect('/profile');
      });
   });

   app.get('/logout', function(req, res) {
      req.logout();
      res.redirect('/');
   });

   app.get('/messages', function(req, res){
      //Message.find({}).populate('poster', 'local.email').exec(function(err, msgs){
      Message.find({}).populate('poster').exec(function(err, msgs){
         if(err) throw err
         res.render('messages', {user: req.user, messages: msgs});
      });
   }).post('/messages', isLoggedIn, function(req, res){
      var msg        = new Message();
      msg.title      = req.body.title;
      msg.body       = req.body.body;
      msg.date       = Date.now();
      msg.poster     = req.user;
      msg.save(function(err){
         if(err) throw err
         res.redirect('/messages');
      });
   });

   app.get('/clubs/list', isLoggedIn, function(req, res){
      Club.find({}).populate('creator').populate('members').exec(function(err, clubs){
         if(err) throw err
         res.render('clubs/list', {user: req.user, clubs: clubs});
      });
   });

   app.get('/clubs/create', checkUser, function(req, res){
      res.render('clubs/create', {user: req.user});
   }).post('/clubs/create', isLoggedIn, function(req, res){
      var club          = new Club();
      club.name         = req.body.name;
      club.description  = req.body.description;
      club.createddate  = Date.now();
      club.creator      = req.user;
      club.members.push(req.user);
      club.save(function(err){
         if(err) throw err;
         res.redirect('/profile');
      }); 
   });

   app.get('/clubs/detail/:id', checkUser, function(req, res){
      var id = req.params.id;
      Club.findById(id).populate('creator').populate('members').exec(function(err, club){
         if(err) throw err
         res.render('clubs/detail', {user: req.user, club: club});
      });
   });

   app.get('/clubs/delete/:id', isLoggedIn, function(req, res){
      console.log('DELETE CLUB');
      var id = req.paramsid;
      Club.findById(id, function(err, club){
         if(err) throw err;
         if(!club) {console.log('club is null?????');return;}
         club.remove(function(err, next){
            if(err) throw err;
            res.redirect('/profile');
         });
      });
      //Club.remove({_id: ObjectID(id)}).exec(function(err, next){
      //   if(err) throw err;
      //   res.redirect('/profile');
      //});
   });


   app.get('/test/:id', 
      function(req, res, next){
         req.isAuthenticated();
         console.log('HERE IS IN THE MIDDLEWARE -- id = ' + req.params.id);
         next();
      }, 
      function(req, res){
         console.log('HERE IS IN THE CALLBACK -- id = ' + req.params.id);
         res.render('index');
      }
   );

};




// route middleware to make sure
function isLoggedIn(req, res, next) {
   // if user is authenticated in the session, carry on
   if (req.isAuthenticated()){
      console.log('Calling req.isAuthenticated method.');
      return next();
   }

   // if they aren't redirect them to the home page
   res.redirect('/');
}

function checkUser(req, res, next) {
   var old_req = req;
   if (req.isAuthenticated()){
      return next();
   }else{
      req = old_req;
      return next();
   }
}


